package com.yunzong.iot.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.yunzong.iot.auth.Auth;
import com.yunzong.iot.mqtt.andmqtt.AndMqtt;
import com.yunzong.iot.mqtt.andmqtt.MqttConnect;
import com.yunzong.iot.mqtt.andmqtt.MqttDisconnect;
import com.yunzong.iot.mqtt.andmqtt.MqttPublish;
import com.yunzong.iot.mqtt.andmqtt.MqttSubscribe;
import com.yunzong.iot.mqtt.andmqtt.MqttUnSubscribe;
import com.yunzong.iot.mqtt.data.Payload;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.IDUtil;
import com.yz.jdd.base.utils.PreferencesUtils;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;

import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import static com.yunzong.iot.mqtt.data.Payload.Data.TYPE_NEW_ORDER;
import static com.yunzong.iot.mqtt.data.Payload.Data.TYPE_PAY_ORDER;


/**
 * @author 克林
 * @version 1.0
 * 心跳服务
 * @date 14点17分
 */
public class HeartBeatService extends Service {

    public static final String TAG = HeartBeatService.class.getSimpleName();

    String deviceId;
    Auth auth;
    MqttConnect mqttConnect;

    /**
     * 消息回调
     */
    MqttCallbackExtended mqttCallbackExtended=new MqttCallbackExtended(){
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {
            Log.i("lkf", "-connectComplete:->连接完成" + serverURI);
        }

        @Override
        public void connectionLost(Throwable cause) {
            Log.i("lkf", "-connectionLost:->连接丢失");
            doMqttConnect(auth);
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {

            if (message != null) {
                String pushStr = new String(message.getPayload());
                Log.i("lkf", "-messageArrived:->收到的消息" + pushStr);
                if (!TextUtils.isEmpty(pushStr)) {
                    Payload payload = new Gson().fromJson(pushStr, Payload.class);
                    if (payload != null) {
                        String type = payload.getType();
                        String id = payload.getId();
                        if (!TextUtils.isEmpty(type) && !TextUtils.isEmpty(id)) {
                            Payload upload = new Payload();
                            upload.setId(id);
                            upload.setType(type);
                            //发布消息，表示我收到了
                            publish(upload);
                        }
                        Payload.Data data = payload.getData();
                        if (data != null) {
                            if (TYPE_NEW_ORDER.equals(data.getType())) {
//                                Intent intent = new Intent("updateNativePage");
//                                intent.putExtra("page", "orderPage");
//                                sendBroadcast(intent);
                                //发消息
                                RxBus.getInstance().send(Events.EVENT_VOICE_BROADCAT, "");
                            }else if(TYPE_PAY_ORDER.equals(data.getType())){
                                if(!TextUtils.isEmpty(data.getContent())){
                                    RxBus.getInstance().send(Events.EVENT_QRCODE_PAY, data.getContent());
                                }

                            }
                        }

                    }
                }
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            try {
                Log.i("lkf", "-deliveryComplete:->消息已送达");

            } catch (Exception e) {
                Log.i("lkf", "-deliveryComplete:->消息已送达" + e.toString());
            }

        }
    };
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * 连接服务器的回调
     */
    IMqttActionListener iMqttActionListener=new IMqttActionListener(){
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.i("lkf", "-onSuccess:->连接成功");
            subscribe();
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            Log.i("lkf", "连接失败exception" + exception);
            doMqttConnect(auth);

        }
    };

    /**
     * 连接服务器
     */
    private void doMqttConnect(Auth auth){
        AndMqtt.getInstance().setMessageListener(mqttCallbackExtended).connect(mqttConnect,
                iMqttActionListener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("lkf", "-onStartCommand:->" + intent);
        if (intent != null) {
            try {
                auth= (Auth) intent.getSerializableExtra("auth");
                mqttConnect=new MqttConnect().setClientId(auth.getClientId())
                        .setUserName(auth.getUserName())
                        .setUserPassword(auth.getPassword())
                        .setKeepAlive(Integer.parseInt(auth.getKeep_alive()))
                        .setTimeout(Integer.parseInt(auth.getConnect_timeout()))
                        .setAutoReconnect(false)
                        .setCleanSession("true".equals(auth.getClean_session()))
                        .setServer(auth.getUrl());
                doMqttConnect(auth);

            } catch (Exception e) {
                Log.e("lkf", "123123" + e.toString());
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 初始化mqtt
     */
    @Override
    public void onCreate() {
        super.onCreate();
        deviceId = PreferencesUtils.getString(this, BaseConfigs.STRING_GUID);
        AndMqtt.getInstance().init(this);

    }

    /**
     * 订阅topic
     */
    private void subscribe() {
        String topic = "/app/" + deviceId + "/cmd";
        Log.e("topic", "" + topic);
        //订阅
        AndMqtt.getInstance().subscribe(new MqttSubscribe()
                .setTopic("/app/" + deviceId + "/cmd")
                .setQos(1), new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.i("lkf", "-onSuccess:->订阅成功");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                try{
                    Log.i("lkf", "-onFailure:->订阅失败" + exception.getCause());
                }catch (Exception e){

                }

            }
        });
    }

    /**
     * 发布收到消息回调
     * @param payload
     */
    private void publish(Payload payload) {
        //发布
        AndMqtt.getInstance().publish(new MqttPublish()
                .setMsg(new Gson().toJson(payload))
                .setQos(1)
                .setTopic("/app/" + deviceId + "/beat"), new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.i("lkf", "-onSuccess:->发布成功");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.i("lkf", "-onFailure:->发布失败");
            }
        });
    }


//        //取消订阅
//        AndMqtt.getInstance().unSubscribe(new MqttUnSubscribe()
//                .setTopic("主题"), new IMqttActionListener() {
//            @Override
//            public void onSuccess(IMqttToken asyncActionToken) {
//                Log.i("lkf", "(MainActivity.java:93)-onSuccess:->取消订阅成功");
//            }
//
//            @Override
//            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//                Log.i("lkf", "(MainActivity.java:98)-onFailure:->取消订阅失败");
//            }
//        });


    @Override
    public void onDestroy() {
        /**
         * 释放连接
         */
        if (AndMqtt.getInstance().isConnect()) {
            AndMqtt.getInstance().disConnect(new MqttDisconnect()
                    .setQuiesceTimeout(0), new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.i("lkf", "(MainActivity.java:98)-onFailure:->断开连接成功");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.i("lkf", "(MainActivity.java:98)-onFailure:->断开连接失败");
                }
            });
            try{
                AndMqtt.getInstance().getMqttClient().unregisterResources();
                AndMqtt.getInstance().getMqttClient().close();
            }catch (Exception e){

            }

            super.onDestroy();
        }

    }
}
